import requests
import json
import time

import lark_oapi as lark
from lark_oapi.api.bitable.v1 import *

class AppRequests:
    def __init__(self, url):
        self.url = url

    def get(self):
        return requests.get(self.url)
    
class AppRequestsFeishu(AppRequests):
    def __init__(self):
        with open('config/config_feishu.json', 'r') as file:
            content = file.read()
            result = json.loads(content)
            self.auth_request = result
        self.expire_time = 0
        self.fs_client = lark.Client.builder() \
        .app_id(self.auth_request['app_id']) \
        .app_secret(self.auth_request['app_secret']) \
        .log_level(lark.LogLevel.DEBUG) \
        .build()

    def request_token(self):
        req_data = {
            "app_id": self.auth_request["app_id"],
            "app_secret": self.auth_request["app_secret"]
        }
        res = requests.request("POST", self.auth_request['token_request_url'],
                         headers={"Content-Type": "application/json;charset=utf-8"},
                         data=json.dumps(req_data))
        print(res.text)
        self.auth_res = json.loads(res.text)
        code = self.auth_res['code']
        self.use_token = self.auth_res['app_access_token']
        expire = self.auth_res['expire']
        self.expire_time = int(time.time()) + expire
        print("test %d %d" % (code, expire))

    def update_duty_data(self, duty_list):
        try:
            duty_data = json.loads(duty_list)
        except ValueError:
            s = duty_list.find('[')
            e = duty_list.find(']')
            duty_r = duty_list[s:e+1]
            duty_data = json.loads(duty_r)

        if len(duty_data) == 0:
            return
        
        now = int(time.time())
        if now >= self.expire_time:
            print("update token")
            self.request_token()

        content = []
        for d in duty_data:
            c = {}
            c['文本'] = d['duty']
            c['日期'] = int(time.time())*1000
            c['科目类别'] = d['class']
            content.append(AppTableRecord.builder()
                .fields(c)
                .build())
        
        request: BatchCreateAppTableRecordRequest = BatchCreateAppTableRecordRequest.builder() \
        .app_token(self.auth_request['app_token']) \
        .table_id(self.auth_request['table_id']) \
        .request_body(BatchCreateAppTableRecordRequestBody.builder()
            .records(content)
            .build()) \
        .build()

        # 发起请求
        response: BatchCreateAppTableRecordResponse = self.fs_client.bitable.v1.app_table_record.batch_create(request)

        # 处理失败返回
        if not response.success():
            lark.logger.error(
                f"client.bitable.v1.app_table_record.batch_create failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}, resp: \n{json.dumps(json.loads(response.raw.content), indent=4, ensure_ascii=False)}")
            return ""

        lark.logger.info(lark.JSON.marshal(response.data, indent=4))
        return response.data


def createServiceFeishu() -> AppRequestsFeishu:
    service = AppRequestsFeishu()
    return service
